import time
from contextlib import contextmanager

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchWindowException
from selenium.webdriver.edge.service import Service as EdgeService


DRIVER_PATH="D:\\auto-test\webdriver\edge\edgedriver_win64-139.9.3405.111\msedgedriver.exe"
class BasePage:
    cookie = {"name": "uuid", "value": "92b42ab9-c144-ef55-a6cb-def15b9d7fd6", "path": "/", "domain": "shopxo.vip",
              "name": "admin_info", "value": "null", "path": "/", "domain": "shopxo.vip", "name": "PHPSESSID",
              "value": "1c04b7cfe72f3c874a2cb523ecf14f5a", "expires": "Sun, 17 Aug 2025 21:34:36 GMT",
              "Max-Age": "43200", "path": "/", "domain": "shopxo.vip"}


    def __init__(self, driver):
        """构造函数，接收WebDriver实例"""
        self.driver = driver
        self.wait = WebDriverWait(driver, 15)
        self.main_window = driver.current_window_handle  # 记录主窗口句柄

    def wait_for_element(self, locator):
        """等待元素可见"""
        return self.wait.until(EC.visibility_of_element_located(locator))

    def wait_for_element_clickable(self, locator):
        """等待元素可点击"""
        return self.wait.until(EC.element_to_be_clickable(locator))

    def click_element(self, locator):
        """点击元素"""
        element = self.wait_for_element_clickable(locator)
        element.click()

    def input_text(self, locator, text):
        """输入文本"""
        element = self.wait_for_element(locator)
        element.clear()
        element.send_keys(text)

    def get_text(self, locator):
        """获取元素文本"""
        element = self.wait_for_element(locator)
        return element.text

    def is_element_present(self, locator):
        """检查元素是否存在"""
        try:
            self.wait_for_element(locator)
            return True
        except TimeoutException:
            return False

    def switch_to_frame(self, locator):
        """切换到iframe"""
        iframe = self.wait_for_element(locator)
        self.driver.switch_to.frame(iframe)

    def switch_to_default_content(self):
        """切换回主文档"""
        self.driver.switch_to.default_content()

    def switch_to_new_window(self, timeout=10):
        """
        切换到最新打开的窗口
        :param timeout: 等待新窗口出现的超时时间
        :return: 新窗口的句柄
        """
        # 记录当前窗口数
        current_count = len(self.driver.window_handles)

        # 等待新窗口出现
        self.wait.until(lambda d: len(d.window_handles) > current_count)

        # 获取所有窗口句柄
        all_windows = self.driver.window_handles

        # 切换到最新窗口（最后一个）
        new_window = all_windows[-1]
        self.driver.switch_to.window(new_window)
        return new_window

    def switch_to_window_by_title(self, title, partial_match=True):
        """
        按标题切换窗口
        :param title: 目标窗口标题
        :param partial_match: 是否部分匹配（默认True）
        :return: 是否切换成功
        """
        for handle in self.driver.window_handles:
            self.driver.switch_to.window(handle)
            current_title = self.driver.title

            if partial_match:
                if title in current_title:
                    return True
            else:
                if title == current_title:
                    return True

        # 未找到匹配窗口
        return False

    def switch_to_window_by_url(self, url_fragment, partial_match=True):
        """
        按URL切换窗口
        :param url_fragment: URL片段
        :param partial_match: 是否部分匹配（默认True）
        :return: 是否切换成功
        """
        for handle in self.driver.window_handles:
            self.driver.switch_to.window(handle)
            current_url = self.driver.current_url

            if partial_match:
                if url_fragment in current_url:
                    return True
            else:
                if url_fragment == current_url:
                    return True

        # 未找到匹配窗口
        return False

    def switch_to_main_window(self):
        """切换回主窗口"""
        if self.main_window in self.driver.window_handles:
            self.driver.switch_to.window(self.main_window)
            return True
        return False

    def close_current_window(self):
        """关闭当前窗口并切换回主窗口"""
        if len(self.driver.window_handles) <= 1:
            raise NoSuchWindowException("无法关闭唯一窗口")

        self.driver.close()
        return self.switch_to_main_window()

    def get_window_count(self):
        """获取当前窗口数量"""
        return len(self.driver.window_handles)

    def wait_for_new_window(self, expected_count, timeout=10):
        """
        等待窗口数量变化
        :param expected_count: 期望的窗口数量
        :param timeout: 超时时间
        :return: 是否达到期望数量
        """
        try:
            self.wait.until(lambda d: len(d.window_handles) == expected_count)
            return True
        except TimeoutException:
            return False

    @contextmanager
    def in_new_window_context(self):
        """
        上下文管理器：临时切换到新窗口
        使用示例：
            with page.in_new_window_context():
                # 在新窗口执行操作
        """
        original_window = self.driver.current_window_handle
        new_window = None

        try:
            # 切换到新窗口
            new_window = self.switch_to_new_window()
            yield self.driver
        finally:
            # 关闭新窗口并返回原窗口
            if new_window and new_window in self.driver.window_handles:
                self.driver.switch_to.window(new_window)
                self.driver.close()
            self.driver.switch_to.window(original_window)



